package cn.jbit.supermarker.web;
//
//import java.io.IOException;
//import java.io.PrintWriter;
//
//import javax.servlet.Servlet;
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//public class UserServlet extends HttpServlet implements Servlet {
//
//	/**
//	 * Constructor of the object.
//	 */
//	public UserServlet() {
//		super();
//	}
//
//	/**
//	 * Destruction of the servlet. <br>
//	 */
//	public void destroy() {
//		super.destroy(); // Just puts "destroy" string in log
//		// Put your code here
//	}
//
//	/**
//	 * The doGet method of the servlet. <br>
//	 *
//	 * This method is called when a form has its tag value method equals to get.
//	 * 
//	 * @param request the request send by the client to the server
//	 * @param response the response send by the server to the client
//	 * @throws ServletException if an error occurred
//	 * @throws IOException if an error occurred
//	 */
//	public void doGet(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//
//		response.setContentType("text/html");
//		PrintWriter out = response.getWriter();
//		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
//		out.println("<HTML>");
//		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
//		out.println("  <BODY>");
//		out.print("    This is ");
//		out.print(this.getClass());
//		out.println(", using the GET method");
//		out.println("  </BODY>");
//		out.println("</HTML>");
//		out.flush();
//		out.close();
//	}
//
//	/**
//	 * The doPost method of the servlet. <br>
//	 *
//	 * This method is called when a form has its tag value method equals to post.
//	 * 
//	 * @param request the request send by the client to the server
//	 * @param response the response send by the server to the client
//	 * @throws ServletException if an error occurred
//	 * @throws IOException if an error occurred
//	 */
//	public void doPost(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//
//		response.setContentType("text/html");
//		PrintWriter out = response.getWriter();
//		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
//		out.println("<HTML>");
//		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
//		out.println("  <BODY>");
//		out.print("    This is ");
//		out.print(this.getClass());
//		out.println(", using the POST method");
//		out.println("  </BODY>");
//		out.println("</HTML>");
//		out.flush();
//		out.close();
//	}
//
//	/**
//	 * Initialization of the servlet. <br>
//	 *
//	 * @throws ServletException if an error occurs
//	 */
//	public void init() throws ServletException {
//		// Put your code here
//	}
//
//}


import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.jms.Session;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.jbit.supermarker.entity.User;
import cn.jbit.supermarker.service.UserService;
import cn.jbit.supermarker.service.impl.UserServiceImpl;
import cn.jbit.supermarker.util.Page;

import com.sun.corba.se.impl.ior.NewObjectKeyTemplateBase;


public class UserServlet extends HttpServlet implements Servlet {

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("flag");
		if ("fenye".equals(action)) {
			this.doPageUser(request, response);
		} else if ("add".equals(action)) {
			this.userAdd(request, response);
		} else if ("toUpdate".equals(action)) {
			this.toUpdate(request, response);
		} else if ("update".equals(action)) {
			this.userUpdate(request, response);
		} else if ("toView".equals(action)) {
			this.toView(request, response);
		} else if ("delete".equals(action)) {
			this.userDelete(request, response);
		} else if ("toUpdatePwd".equals(action)) {
			this.toUpdatePwd(request, response);
		} else if ("updatePwd".equals(action)) {
			this.updatePwd(request, response);
		} else if ("login".equals(action)) {
			this.userLogin(request, response);
		}else if ("userUpdatePwd".equals(action)) {
			this.userUpdatePwd(request, response);
		}else if ("exists".equals(action)) {
			this.doExists(request, response);
		}
	}

	/**
	 * 用戶登錄
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void userLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String loginName = request.getParameter("loginName");
		String loginPwd = request.getParameter("loginPwd");

		UserService userService = new UserServiceImpl();
		User user = userService.login(loginName, loginPwd);
//		response.setContentType("text/html;charset=UTF-8;");
//		PrintWriter out = response.getWriter();
		if (user == null) {
			request.setAttribute("msg", "用户名或密码出错，请重试！");
			request.getRequestDispatcher("login.jsp").forward(request, response);
//			out.print("<script type='text/javascript'>  alert('用户名或密码出错，请重试！');</script>");
//			out.flush();
//			out.close();
			
		} else {
			//把用户保存在session中
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			request.getRequestDispatcher("frame.jsp").forward(request, response);

		}
	}

	// 分页显示用户列表
	public void doPageUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String currentPage = request.getParameter("pageIndex");
		if (currentPage == null || "".equals(currentPage)) {
			currentPage = "1";
		}
		int pageIndex = Integer.parseInt(currentPage);
		if (pageIndex < 1) {
			pageIndex = 1;
		}
		UserServiceImpl userService = new UserServiceImpl();
		String userName = request.getParameter("userName");
		int total = userService.getTotalCount(userName);
		int pageSize = 2;

		Page pages = new Page();
		pages.setPageSize(pageSize);
		pages.setTotalCount(total);
		int totalPage = pages.getTotalPageCount();
		if (pageIndex > totalPage) {
			pageIndex = totalPage;
		}
		pages.setCurrPageNo(pageIndex);
		// String name=request.getParameter("userName");
		List<User> userList = userService.getUserPageList(pageIndex, pageSize,
				userName);
		
		request.setAttribute("userList", userList);
		request.setAttribute("pages", pages);
		request.setAttribute("userName", userName);
		request.getRequestDispatcher("userList.jsp").forward(request, response);
	}

	// 添加用户
	public void userAdd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserServiceImpl userService = new UserServiceImpl();
		User user = new User();
		String birthDate = request.getParameter("birthDate");
		user.setBirthdate(birthDate);
		user.setAddree(request.getParameter("address"));
		user.setGender(Integer.parseInt(request.getParameter("gender")));
		user.setLoginnane(request.getParameter("loginName"));
		user.setLoginpwd(request.getParameter("password"));
		user.setName(request.getParameter("name"));
		user.setPhone(request.getParameter("phone"));
		user.setUser_type(Integer.parseInt(request.getParameter("user_type")));
		boolean flag = userService.addUser(user);
		response.setContentType("text/html;charset=UTF-8;");
		PrintWriter out = response.getWriter();
		if (flag) {
			out.print("<script type='text/javascript'>  alert('添加成功'); window.location='UserServlet?flag=fenye' ;</script>");
		} else {
			out.print("<script type='text/javascript'>  alert('添加失败'); window.location='userAdd.jsp' ;</script>");
		}
		out.flush();
		out.close();
	}

	// 展示页面
	public void toView(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserServiceImpl userService = new UserServiceImpl();
		User user = userService.getUserById(Integer.parseInt(request
				.getParameter("id")));

		request.setAttribute("user", user);
		request.getRequestDispatcher("userView.jsp").forward(request, response);
	}

	// 展示修改页面
	public void toUpdate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UserService userService = new UserServiceImpl();
		User user = userService.getUserById(Integer.parseInt(request
				.getParameter("id")));
		request.setAttribute("user", user);
		request.getRequestDispatcher("userUpdate.jsp").forward(request,
				response);
	}

	// 修改
	public void userUpdate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UserServiceImpl userService = new UserServiceImpl();
		String id = request.getParameter("userId");
		User user = userService.getUserById(Integer.parseInt(id));
		user.setAddree(request.getParameter("address"));
		user.setBirthdate(request.getParameter("birthDate"));
		user.setName(request.getParameter("name"));
		user.setPhone(request.getParameter("phone"));
		user.setUser_type(Integer.parseInt(request.getParameter("userType")));
		user.setGender(Integer.parseInt(request.getParameter("gender")));
		boolean flag = userService.updateUser(user);
		response.setContentType("text/html;charset=UTF-8;");
		PrintWriter out = response.getWriter();
		if (flag) {
			out.print("<script type='text/javascript'>  alert('修改成功'); window.location='UserServlet?flag=fenye' ;</script>");
		} else {
			out.print("<script type='text/javascript'>  alert('修改失败'); window.location='UserServlet?flag=fenye' ;</script>");
		}
		out.flush();
		out.close();
	}

	// 删除
	public void userDelete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8;");
		PrintWriter out = response.getWriter();
		String id = request.getParameter("id");
		if (id != null && !"".equals(id)) {
			UserServiceImpl userService = new UserServiceImpl();
			boolean flag = userService.deleteUser(Integer.parseInt(id));
			if (flag) {
				out.println("<script type='text/javascript'> alert('删除成功');window.location='UserServlet?flag=fenye' ;</script>");
			} else {
				out.println("<script type='text/javascript'> alert('删除失败');window.location='UserServlet?flag=fenye' ;</script>");
			}
			out.flush();
			out.close();
		}
	}

	// 进入修改，密码页面
	public void toUpdatePwd(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UserService userService = new UserServiceImpl();
		User user = userService.getUserById(Integer.parseInt(request
				.getParameter("id")));
		request.setAttribute("user", user);
		request.getRequestDispatcher("updatePwd.jsp")
				.forward(request, response);
	}

	// 修改密码
	public void updatePwd(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UserServiceImpl userService = new UserServiceImpl();
		String id = request.getParameter("id");
		System.out.println(id);
		User user = userService.getUserById(Integer.parseInt(id));
		user.setLoginpwd(request.getParameter("newPassword"));
		boolean flag = userService.updateUser(user);
		response.setContentType("text/html;charset=UTF-8;");
		PrintWriter out = response.getWriter();
		if (flag) {
			out.print("<script type='text/javascript'>  alert('修改成功'); window.location='UserServlet?flag=fenye' ;</script>");
		} else {
			out.print("<script type='text/javascript'>  alert('修改失败'); window.location='updatePwd.jsp' ;</script>");
		}
		out.flush();
		out.close();
	}
	//用户修改密码
	public void userUpdatePwd(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		HttpSession session=request.getSession();//获取session对象
		Object object=session.getAttribute("user");//得到保存在session中的user
		User user=(User)object;//强制类型转换为user
		UserServiceImpl userService=new UserServiceImpl();
		String oldPassword=request.getParameter("oldPassword");
		boolean flag=false;
		if(user.getLoginpwd().equals(oldPassword)){
			String newPassword=request.getParameter("newPassword");
			user.setLoginpwd(newPassword);
			 flag=userService.updateUser(user);
		}
		response.setContentType("text/html;charset=UTF-8;");
		PrintWriter out = response.getWriter();
		if (flag) {
			out.print("<script type='text/javascript'>  alert('修改成功'); window.location='UserServlet?flag=fenye' ;</script>");
		} else {
			out.print("<script type='text/javascript'>  alert('修改失败'); window.location='userUpdatePwd.jsp' ;</script>");
		}
		out.flush();
		out.close();
		} 
	
	public void doExists(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		UserService userService = new UserServiceImpl();
		User user=userService.searchLogName(request.getParameter("loginName"));
		response.setContentType("text/html;charset=UTF-8;");
		PrintWriter out = response.getWriter();
		if(user!=null){
			out.print("true");
		}else{
			out.print("false");
		}
		out.flush();
		out.close();
		
	}
	
	
	
	public void init() throws ServletException {
		// Put your code here
	}

}
